package jsonrpc

import (
	"fmt"
	"lib/exception"
	"lib/logger"
)

var commandHandlers map[string]RpcHandler

type RegisterHandlerParam struct {
	methodName string
	callback   RpcHandler
}

// RegisterRpcHandler
// register all jsonrpc handler
func RegisterRpcHandler(methodName string, handler RpcHandler) {
	if commandHandlers == nil {
		commandHandlers = map[string]RpcHandler{}
	}
	if len(methodName) <= 0 {
		logger.Errorf("RegisterRpcHandlerErr methodName is null")
		return
	}
	if handler.Command == nil || handler.Decoder == nil {
		logger.Errorf("RegisterRpcHandlerErr RpcHandler maybe null")
		return
	}
	if _, existed := commandHandlers[methodName]; existed {
		logger.Errorf("RegisterRpcHandlerErr RpcHandler maybe already exist")
		return
	}
	commandHandlers[methodName] = handler
}

// GetRpcHandler
// get jsonrpc handler by methodName
func GetRpcHandler(methodName string) (RpcHandler, exception.Exception) {
	if commandHandlers == nil {
		logger.Errorf("RegisterRpcHandlerErr RpcHandler maybe already exist.")
		return RpcHandler{}, exception.NewException(fmt.Sprintf("GetRpcHandler RpcHandlerMap is null"), 111)
	}
	if _, existed := commandHandlers[methodName]; !existed {
		logger.Errorf("RegisterRpcHandlerErr RpcHandler %v Not Found.", methodName)
		return RpcHandler{}, exception.NewException(fmt.Sprintf("RegisterRpcHandlerErr RpcHandler %v Not Found.", methodName), 111)
	}
	return commandHandlers[methodName], nil
}
